import 'package:shared_preferences/shared_preferences.dart';
import '../constants/index.dart';

class TokenManager {
  //定义变量
  String _token = '';
  String _refreshToken = '';
  // 初始化首选项实例
  Future<SharedPreferences> _getInstance() {
    return SharedPreferences.getInstance();
  }

//启动项目是进行初始化
  init() async {
    final instance = await _getInstance();
    _token = instance.getString(GlobalVariable.TOKEN) ?? '';
    _refreshToken = instance.getString(GlobalVariable.REFRSHTOKE) ?? '';
  }

  // 存储token
  setToken(String token, {String? refreshToken}) async {
    // 获取首选项实例
    final instance = await _getInstance();
    // 基于实例 存储
    instance.setString(GlobalVariable.TOKEN, token);
    _token = token;
    if (refreshToken != null) {
      instance.setString(GlobalVariable.REFRSHTOKE, refreshToken);
      _refreshToken = refreshToken;
    }
  }

// 获取token
  getToken() {
    return _token ?? '';
  }

//  获取refreshToken
  getRefreshToken() {
    return _refreshToken ?? '';
  }

  // 删除token
  deleteToken() async {
    // 获取首选项实例
    final instance = await _getInstance();
    instance.remove(GlobalVariable.TOKEN);
    _token = '';
    instance.remove(GlobalVariable.REFRSHTOKE);
    _refreshToken = '';
  }
}

final tokenManager = TokenManager();
